//
//  ZhListController.swift
//  mggz
//
//  Created by Apple on 2018/4/25.
//  Copyright © 2018年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import SVProgressHUD
import MJRefresh
import RxSwift
import RxCocoa

class ZhListController: UIViewController {

    @IBOutlet weak var useMoney: UILabel!
    @IBOutlet weak var tableview: UITableView!
    @IBOutlet weak var projectName: UILabel!
    @IBOutlet weak var line:UIView!
    
    
    var dataCount = [ZhListitem]()
    var datavariable:PublishSubject<[ZhListitem]> = PublishSubject()
    
    var emptyView:EmptyView?
    var paramslist = [String:Any]()
    var page:Int? = 1
    override func viewDidLoad() {
        super.viewDidLoad()

        self.tableview.register(UINib(nibName: "ZhuhuCell", bundle: nil), forCellReuseIdentifier: "cell")
        self.tableview.separatorStyle = .singleLine
        self.tableview.rowHeight = 70
        self.tableview.tableFooterView = UIView(frame: CGRect.zero)
        
        let tablehead = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(refresh))
        tablehead?.stateLabel.isHidden = true
        self.tableview.mj_header = tablehead
        
        let tablefoot = MJRefreshBackNormalFooter(refreshingTarget: self, refreshingAction: #selector(loadMore))
        tablefoot?.stateLabel.isHidden = true
        self.tableview.mj_footer = tablefoot
        
        
        self.datavariable.asObservable().bind(to: self.tableview.rx.items){
            (_,row,element) in
            let cell = self.tableview.dequeueReusableCell(withIdentifier: "cell", for: IndexPath(row : row, section : 0)) as! ZhuhuCell
            cell.dataItem = element
            cell.selectionStyle = .none
            return cell
        }
        
        SVProgressHUD.setDefaultMaskType(.clear)
        
        self.getTotalData()
    }
    
    @objc func refresh(){
        self.page = 1
        self.getzhlist()
    }
    @objc func loadMore(){
        self.page! += 1
        self.getzhlist()
    }
    
    
    func getTotalData(){
        var params:[String:Any] = ["constructionProjectID":ProjectId as! String]
        MNetHttp.sharedInstance.postSingle(API_CALL_METHOD, method: .ZhTotal, params: &params, type: ZhTotal.self, success: { (bean,_) in
            
            guard let b = bean as? ZhTotal else{
                return
            }
            
            self.projectName.text = "专户所属项目："+(b.Result?.ProjectName ?? "")
            self.useMoney.text = "当前余额(元)："+(b.Result?.ResidualAmount?.roundTo(2) ?? "")
            self.getzhlist()
            
        }) { (error) in
            switch error{
            case .HTTPERROR:
                self.addEmptydata("网络异常")
                break
            case .DATAERROR:
                self.addEmptydata("数据异常")
                break
            case .DATAFAIL:
                self.addEmptydata()
                break
            case .StateFail(let obj):
                guard let data = obj as? [String:Any] else{
                    self.addEmptydata("网络异常")
                    return
                }
                self.addEmptydata(data["Msg"] as? String ?? "")
                break
            }
        }
    }
    
    func getzhlist(){
        self.paramslist["pageIndex"] = String(format: "%d", self.page!)
        self.paramslist["pageSize"] = String(format:"%d",PageSize)
        self.paramslist["constructionProjectID"] = ProjectId ?? ""
        MNetHttp.sharedInstance.postSingle(API_CALL_METHOD, method: .ZhDetail, params: &self.paramslist, type: ZhList.self, success: { (bean,_) in
            
            guard let b = bean as? ZhList else{
                
                return
            }
            
            if (b.Result?.Total ?? 0) == 0{
                self.addEmptyStyle2()
            } else{
                if self.page == 1{
                    self.dataCount.removeAll()
                    self.tableview.mj_header.endRefreshing()
                    self.tableview.mj_footer.endRefreshing()
                    
                }
                if (b.Result?.SalaryList?.count ?? 0) < PageSize{
                    self.tableview.mj_footer.endRefreshingWithNoMoreData()
                }
                
                
                self.dataCount.append(contentsOf: (b.Result?.SalaryList)!)
                self.datavariable.onNext(self.dataCount)
            }
            
        }) { (error) in
            switch error{
            case .DATAERROR:
                self.addEmptyStyle2("数据异常")
                break
            case .DATAFAIL:
                self.addEmptyStyle2("后台异常")
                break
            case .HTTPERROR:
                self.addEmptyStyle2("网络异常")
                break
            case .StateFail(let obj):
                guard let data = obj as? [String:Any] else{
                    self.addEmptydata("网络异常")
                    return
                }
                self.addEmptydata(data["Msg"] as? String ?? "")
                break
            }
        }
    }
    
    func addEmptydata(_ status:String = "该项目未开通专户"){
        if self.emptyView != nil {
            self.emptyView?.removeFromSuperview()
            self.emptyView = nil
        }else{
            self.emptyView = EmptyView(frame: CGRect.zero, _title: status, _top: Float(ScreenWidth/4))
            self.view.addSubview(self.emptyView!)
            self.emptyView?.snp.updateConstraints({ (make) in
                make.top.equalTo(self.view.snp.top)
                make.left.equalTo(self.view.snp.left)
                make.right.equalTo(self.view.snp.right)
                make.bottom.equalTo(self.view.snp.bottom)
            })
        }
    }
    
    func addEmptyStyle2(_ status:String = "暂无专户明细"){
        if self.emptyView != nil {
            self.emptyView?.removeFromSuperview()
            self.emptyView = nil
        }else{
            self.emptyView = EmptyView(frame: CGRect.zero, _title: status, _top: Float(ScreenWidth/4))
            self.view.addSubview(self.emptyView!)
            self.emptyView?.snp.updateConstraints({ (make) in
                make.top.equalTo(self.line.snp.bottom)
                make.left.equalTo(self.view.snp.left)
                make.right.equalTo(self.view.snp.right)
                make.bottom.equalTo(self.view.snp.bottom)
            })
        }
    }
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
